<script lang="ts" setup>
import type { BillApi } from '#/api/spa/bill';
import type { Rule } from 'ant-design-vue/es/form';

import { useVbenModal } from '@vben/common-ui';
import { Tinymce as RichTextarea } from '#/components/tinymce';
import { ImageUpload, FileUpload } from '#/components/upload';
import {
  message,
  Tabs,
  Form,
  Input,
  Textarea,
  Select,
  RadioGroup,
  Radio,
  CheckboxGroup,
  Checkbox,
  DatePicker,
  TreeSelect,
} from 'ant-design-vue';
import BillItemsForm from './bill-items-form.vue';

import { computed, ref } from 'vue';
import { $t } from '#/locales';
import { getBill, createBill, updateBill } from '#/api/spa/bill';

const emit = defineEmits(['success']);

const formRef = ref();
const formData = ref<Partial<BillApi.Bill>>({
  id: undefined,
  billNumber: undefined,
  handCardId: undefined,
  memberId: undefined,
  roomNumber: undefined,
  totalAmount: undefined,
  discountAmount: undefined,
  actualAmount: undefined,
  paymentMethod: undefined,
  paymentStatus: undefined,
  openTime: undefined,
  closeTime: undefined,
  durationMinutes: undefined,
  pointsEarned: undefined,
  pointsUsed: undefined,
  remarks: undefined,
});
const rules: Record<string, Rule[]> = {
  billNumber: [{ required: true, message: '账单号不能为空', trigger: 'blur' }],
  handCardId: [{ required: true, message: '手牌ID不能为空', trigger: 'blur' }],
  totalAmount: [{ required: true, message: '总金额不能为空', trigger: 'blur' }],
  actualAmount: [
    { required: true, message: '实收金额不能为空', trigger: 'blur' },
  ],
  paymentMethod: [
    { required: true, message: '支付方式不能为空', trigger: 'blur' },
  ],
  paymentStatus: [
    { required: true, message: '支付状态不能为空', trigger: 'blur' },
  ],
  openTime: [{ required: true, message: '开房时间不能为空', trigger: 'blur' }],
};
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['结算账单'])
    : $t('ui.actionTitle.create', ['结算账单']);
});

/** 子表的表单 */
const subTabsName = ref('billItems');
const billItemsFormRef = ref<InstanceType<typeof BillItemsForm>>();

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    billNumber: undefined,
    handCardId: undefined,
    memberId: undefined,
    roomNumber: undefined,
    totalAmount: undefined,
    discountAmount: undefined,
    actualAmount: undefined,
    paymentMethod: undefined,
    paymentStatus: undefined,
    openTime: undefined,
    closeTime: undefined,
    durationMinutes: undefined,
    pointsEarned: undefined,
    pointsUsed: undefined,
    remarks: undefined,
  };
  formRef.value?.resetFields();
};

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    await formRef.value?.validate();
    // 校验子表单
    modalApi.lock();
    // 提交表单
    const data = formData.value as BillApi.Bill;
    // 拼接子表的数据
    data.billItemss = billItemsFormRef.value?.getData();
    try {
      await (formData.value?.id ? updateBill(data) : createBill(data));
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success({
        content: $t('ui.actionMessage.operationSuccess'),
        key: 'action_process_msg',
      });
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      resetForm();
      return;
    }
    // 加载数据
    let data = modalApi.getData<BillApi.Bill>();
    if (!data) {
      return;
    }
    if (data.id) {
      modalApi.lock();
      try {
        data = await getBill(data.id);
      } finally {
        modalApi.unlock();
      }
    }
    formData.value = data;
  },
});
</script>

<template>
  <Modal :title="getTitle">
    <Form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 18 }"
    >
      <Form.Item label="账单号" name="billNumber">
        <Input v-model:value="formData.billNumber" placeholder="请输入账单号" />
      </Form.Item>
      <Form.Item label="手牌ID" name="handCardId">
        <Input v-model:value="formData.handCardId" placeholder="请输入手牌ID" />
      </Form.Item>
      <Form.Item label="会员ID" name="memberId">
        <Input v-model:value="formData.memberId" placeholder="请输入会员ID" />
      </Form.Item>
      <Form.Item label="房间号" name="roomNumber">
        <Input v-model:value="formData.roomNumber" placeholder="请输入房间号" />
      </Form.Item>
      <Form.Item label="总金额" name="totalAmount">
        <Input
          v-model:value="formData.totalAmount"
          placeholder="请输入总金额"
        />
      </Form.Item>
      <Form.Item label="优惠金额" name="discountAmount">
        <Input
          v-model:value="formData.discountAmount"
          placeholder="请输入优惠金额"
        />
      </Form.Item>
      <Form.Item label="实收金额" name="actualAmount">
        <Input
          v-model:value="formData.actualAmount"
          placeholder="请输入实收金额"
        />
      </Form.Item>
      <Form.Item label="支付方式" name="paymentMethod">
        <Input
          v-model:value="formData.paymentMethod"
          placeholder="请输入支付方式"
        />
      </Form.Item>
      <Form.Item label="支付状态" name="paymentStatus">
        <RadioGroup v-model:value="formData.paymentStatus">
          <Radio value="1">请选择字典生成</Radio>
        </RadioGroup>
      </Form.Item>
      <Form.Item label="开房时间" name="openTime">
        <DatePicker
          v-model:value="formData.openTime"
          valueFormat="x"
          placeholder="选择开房时间"
        />
      </Form.Item>
      <Form.Item label="结账时间" name="closeTime">
        <DatePicker
          v-model:value="formData.closeTime"
          valueFormat="x"
          placeholder="选择结账时间"
        />
      </Form.Item>
      <Form.Item label="消费时长(分钟)" name="durationMinutes">
        <Input
          v-model:value="formData.durationMinutes"
          placeholder="请输入消费时长(分钟)"
        />
      </Form.Item>
      <Form.Item label="获得积分" name="pointsEarned">
        <Input
          v-model:value="formData.pointsEarned"
          placeholder="请输入获得积分"
        />
      </Form.Item>
      <Form.Item label="使用积分" name="pointsUsed">
        <Input
          v-model:value="formData.pointsUsed"
          placeholder="请输入使用积分"
        />
      </Form.Item>
      <Form.Item label="备注" name="remarks">
        <Input v-model:value="formData.remarks" placeholder="请输入备注" />
      </Form.Item>
    </Form>
    <!-- 子表的表单 -->
    <Tabs v-model:active-key="subTabsName">
      <Tabs.TabPane key="billItems" tab="账单明细" force-render>
        <BillItemsForm ref="billItemsFormRef" :bill-id="formData?.id" />
      </Tabs.TabPane>
    </Tabs>
  </Modal>
</template>
